import React, { useState, Fragment } from 'react';
import { connect } from 'dva';
import { Modal, Popover, Button, Icon, Popconfirm, Tooltip, Divider, Row, Col } from 'antd';
import {
  Form,
  FormItem,
  createFormActions,
  FormEffectHooks,
  // InternalFieldList as FieldList,
} from '@formily/antd';
import { Radio, Switch, Input, Range, NumberPicker, Select } from '@formily/antd-components';
import classNames from 'classnames';
import throttle from 'lodash/throttle';
// import { resetSpan } from '../utils';
import styles from '../../styles.less';

const actions = createFormActions();

const { onFieldValueChange$, onFormInputChange$, onFieldInputChange$ } = FormEffectHooks;

function ForForm({
  dispatch,
  vertical = true,
  columnNum = 3,
  labelWidth = 0,
  submitUrl,
  saveUrl,
  needSubmit,
  needSave,
  needBack,
}) {
  const [actived, setActived] = useState(false);

  return (
    <Form
      initialValues={{
        vertical,
        columnNum: typeof columnNum === 'number' ? columnNum : 3,
        labelWidth: typeof labelWidth === 'number' ? labelWidth : 0,
        submitUrl,
        saveUrl,
        needSubmit,
        needSave,
        needBack,
      }}
      className={classNames(styles.configForm)}
      actions={actions}
      colon={false}
      effects={({ setFieldState }) => {
        // 只监控人工操作引起的FormItem值变化
        onFieldInputChange$('*').subscribe(
          throttle(
            async ({ name }) => {
              await actions.validate({ silent: true });
              // actions.getFormState().valid取到的结果是异步的，所以必须用到await actions.validate才能得到精确的结果
              const isValid = actions.getFormState().valid;

              // 校验失败
              if (!isValid) {
                return;
              }

              // 重置每个formItem的megaProps.span = 1; 同时更新forForm相关的字段
              if (name === 'columnNum') {
                dispatch({
                  type: 'formDesigner/updateSpan',
                  payload: actions.getFormState().values,
                });
              } else {
                dispatch({
                  type: 'formDesigner/update',
                  payload: actions.getFormState().values,
                });
              }
            },
            300,
            { trailing: true, leading: false }
          )
        );

        // 垂直布局 不显示label和wrapper的col配置项
        onFieldValueChange$('vertical').subscribe(({ value: checked }) => {
          setFieldState('labelWidth', state => {
            state.visible = !checked;
          });
        });

        //
        // onFieldValueChange$('submitUrl').subscribe(({ value }) => {
        //   setFieldState('needBack', state => {
        //     state.display = !!value;
        //   });
        // });

        //
        // onFieldValueChange$('needSave').subscribe(({ value: checked }) => {
        //   setFieldState('saveUrl', state => {
        //     state.visible = checked;
        //   });
        // });
      }}
    >
      <FormItem
        label="布局"
        name="vertical"
        triggerType="onChange"
        component={Radio.Group}
        dataSource={[
          { label: '内联', value: false },
          { label: '垂直', value: true },
        ]}
      />

      <FormItem
        label="标题长度"
        name="labelWidth"
        min={0}
        initialValue={120} // 0表示不限制
        triggerType="onChange"
        component={NumberPicker}
        formatter={value => `${value} px`}
        parser={value => value.replace(' px', '')}
      />

      <FormItem
        label={
          <span>
            列数
            {!actived ? (
              <Popconfirm
                placement="left"
                title="修改【列数】，将重置所有子元素的【水平跨度】"
                onConfirm={() => setActived(true)}
                okText="知道了"
              >
                <a style={{ marginLeft: '100px' }}>激活</a>
              </Popconfirm>
            ) : (
              <a style={{ marginLeft: '100px' }} onClick={() => setActived(false)}>
                关闭
              </a>
            )}
          </span>
        }
        name="columnNum"
        min={1}
        max={4}
        triggerType="onChange"
        component={Range}
        disabled={!actived}
        style={{ width: '150px' }}
        marks={{ 1: 1, 2: 2, 3: 3, 4: 4 }}
      />

      {/* <Divider style={{ fontSize: 14 }}>提交配置</Divider> */}

      {/* <FormItem
        label="提交地址"
        name="submitUrl"
        allowClear
        min={0}
        triggerType="onChange"
        component={Input}
        // rules={[{ required: true, whitespace: true, message: '必填项' }]}
        placeholder="无"
      />

      <FormItem
        label="保存地址"
        name="saveUrl"
        triggerType="onChange"
        component={Input}
        allowClear
      /> */}

      <FormItem
        label="提交按钮"
        name="needSubmit"
        triggerType="onChange"
        component={Switch}
        initialValue
      />

      <FormItem
        label="保存按钮"
        name="needSave"
        triggerType="onChange"
        component={Switch}
        initialValue={false}
      />

      <FormItem
        label={
          <>
            返回按钮
            <Tooltip title="点击执行onBack回调函数">
              <Icon type="info-circle" className={styles.helpIcon} />
            </Tooltip>
          </>
        }
        name="needBack"
        triggerType="onChange"
        component={Switch}
        initialValue={false}
      />

      {/* <FieldList name="extraAction">
        {({ state, mutators }) => {
          const onAdd = () => mutators.push();
          const onRemove = index => mutators.remove(index);
          return (
            <Fragment>
              <Button className="margin-bottom" type="dashed" icon="plus" block onClick={onAdd}>
                添加按钮
              </Button>
              {state.value.length > 0 ? (
                <div className="text-gray margin-bottom">点击对应按钮，编辑属性</div>
              ) : null}
              {state.value.map((item, index) => (
                <Popover
                  // eslint-disable-next-line react/no-array-index-key
                  key={index}
                  title={`按钮${index + 1}`}
                  trigger="click"
                  placement="left"
                  overlayStyle={{ width: 500 }}
                  content={
                    <>
                      <Row gutter={16}>
                        <Col span={12}>
                          <FormItem
                            label="名称"
                            placeholder="请输入"
                            name={`extraAction.${index}.title`}
                            triggerType="onChange"
                            component={Input}
                          />
                        </Col>
                        <Col span={12}>
                          <FormItem
                            label="风格"
                            placeholder="请选择"
                            name={`extraAction.${index}.buttonType`}
                            triggerType="onChange"
                            component={Select}
                            dataSource={[
                              {
                                label: 'Default',
                                value: 'default',
                              },
                              {
                                label: 'Primary',
                                value: 'primary',
                              },
                              {
                                label: 'Link',
                                value: 'link',
                              },
                              {
                                label: 'Dashed',
                                value: 'dashed',
                              },
                              {
                                label: 'Danger',
                                value: 'danger',
                              },
                            ]}
                          />
                        </Col>
                      </Row>
                      <Row gutter={16}>
                        <Col span={12}>
                          <FormItem
                            label={
                              <>
                                异步请求
                                <Tooltip title="点击时执行异步请求">
                                  <Icon type="info-circle" className={styles.helpIcon} />
                                </Tooltip>
                              </>
                            }
                            placeholder="请输入url"
                            name={`extraAction.${index}.asyncUrl`}
                            triggerType="onChange"
                            component={Input}
                          />
                        </Col>
                        <Col span={12}>
                          <FormItem
                            label="请求类型"
                            initialValue="post"
                            name={`extraAction.${index}.method`}
                            triggerType="onChange"
                            component={Select}
                            dataSource={[
                              { label: 'post', value: 'post' },
                              { label: 'get', value: 'get' },
                              { label: 'put', value: 'put' },
                            ]}
                          />
                        </Col>
                      </Row>
                      <Row gutter={16}>
                        <Col span={12}>
                          <FormItem
                            label={
                              <>
                                动作内容
                                <Tooltip title="异步请求结束后执行的动作">
                                  <Icon type="info-circle" className={styles.helpIcon} />
                                </Tooltip>
                              </>
                            }
                            placeholder="请选择"
                            name={`extraAction.${index}.actionType`}
                            triggerType="onChange"
                            component={Select}
                            dataSource={[
                              {
                                label: '显示弹窗',
                                value: 'modal',
                              },
                            ]}
                          />
                        </Col>
                        <Col span={12}>
                          <Button
                            type="link"
                            className="text-danger"
                            onClick={() => {
                              onRemove(index);
                            }}
                          >
                            删除
                          </Button>
                        </Col>
                      </Row>
                    </>
                  }
                >
                  <Button type="dashed" className="margin">{`按钮${index + 1}`}</Button>
                </Popover>
              ))}
            </Fragment>
          );
        }}
      </FieldList> */}
    </Form>
  );
}

export default connect(({ formDesigner }) => ({
  vertical: formDesigner.vertical,
  columnNum: formDesigner.columnNum,
  labelWidth: formDesigner.labelWidth,
  submitUrl: formDesigner.submitUrl,
  saveUrl: formDesigner.saveUrl,
  needSubmit: formDesigner.needSubmit,
  needSave: formDesigner.needSave,
  needBack: formDesigner.needBack,
}))(ForForm);
